<template>
  <div class="announcements-container">
    <!-- 导航栏 -->
    <Navbar />

    <!-- 为保持与其他页面导航一致，移除自定义导航链接 -->
    <!-- 导航链接将使用 Navbar 组件的默认实现 -->

    <!-- 内容区域 -->
    <div class="content-wrapper">
      <h1 class="page-title">公告列表</h1>

      <!-- 公告列表 -->
      <div v-if="loading" class="loading-indicator">加载中...</div>
      <div v-else-if="announcements.length === 0" class="no-data">暂无公告数据</div>
      <div v-else class="announcement-list">
        <div v-for="announcement in announcements" :key="announcement.announcement_id" class="announcement-item" @click="viewDetail(announcement.announcement_id)">
          <div class="announcement-header">
            <h2>{{ announcement.title }}</h2>
            <span v-if="announcement.is_top" class="top-tag">置顶</span>
          </div>
          <div class="announcement-meta">
            <span>发布时间: {{ formatDate(announcement.publish_time) }}</span>
            <span v-if="announcement.expire_time">过期时间: {{ formatDate(announcement.expire_time) }}</span>
          </div>
          <div class="announcement-content">
            {{ truncateContent(announcement.content) }}
          </div>
          <div class="announcement-footer">
            <span>查看次数: {{ announcement.view_count }}</span>
          </div>
        </div>
      </div>

      <!-- 分页控件 -->
      <div v-if="pagination" class="pagination-controls">
        <button @click="changePage(1)" :disabled="pagination.currentPage === 1">首页</button>
        <button @click="changePage(pagination.currentPage - 1)" :disabled="pagination.currentPage === 1">上一页</button>
        <span v-for="pageNum in pageRange" :key="pageNum" :class="{ 'active': pageNum === pagination.currentPage }" @click="changePage(pageNum)">{{ pageNum }}</span>
        <button @click="changePage(pagination.currentPage + 1)" :disabled="pagination.currentPage === pagination.totalPages">下一页</button>
        <button @click="changePage(pagination.totalPages)" :disabled="pagination.currentPage === pagination.totalPages">末页</button>
        <span class="page-info">共 {{ pagination.totalPages }} 页 / {{ pagination.totalItems }} 条</span>
      </div>
    </div>

    <!-- 公告详情弹窗 -->
    <div v-if="showDetail" class="modal-overlay" @click="closeDetail">
      <div class="modal-content" @click.stop>
        <button class="close-btn" @click="closeDetail">×</button>
        <h2 class="detail-title">{{ currentAnnouncement?.title }}</h2>
        <div class="detail-meta">
          <span>发布时间: {{ formatDate(currentAnnouncement?.publish_time) }}</span>
          <span v-if="currentAnnouncement?.expire_time">过期时间: {{ formatDate(currentAnnouncement?.expire_time) }}</span>
        </div>
        <div class="detail-content" v-html="currentAnnouncement?.content"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">// 导入依赖
import Navbar from '../components/Navbar.vue';
import { ref, onMounted, onUnmounted, computed } from 'vue';
import axios from 'axios';
import moment from 'moment';

// 响应式变量
const announcements = ref<Array<{
  announcement_id: number;
  title: string;
  content: string;
  author_id: number;
  is_top: number;
  status: number;
  view_count: number;
  publish_time: string;
  expire_time: string | null;
  created_at: string;
  updated_at: string;
}>>([]);
const loading = ref(true);
const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000';
const currentPage = ref(1);
const pageSize = ref(10);
const pagination = ref<{
  currentPage: number;
  pageSize: number;
  totalItems: number;
  totalPages: number;
} | null>(null);
const showDetail = ref(false);
const currentAnnouncement = ref<{
  announcement_id: number;
  title: string;
  content: string;
  author_id: number;
  is_top: number;
  status: number;
  view_count: number;
  publish_time: string;
  expire_time: string | null;
  created_at: string;
  updated_at: string;
} | null>(null);

/**
 * 获取公告列表
 */
const fetchAnnouncements = async () => {
  try {
    loading.value = true;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Announcements] 开始请求获取公告列表: 页码=${currentPage.value}, 每页数量=${pageSize.value}`);
    
    const apiUrl = `${API_BASE}/api/announcements`;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Announcements] 请求URL: ${apiUrl}`);
    
    const response = await axios.get(apiUrl, {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    });
    
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Announcements] 公告列表请求成功，状态码: ${response.status}`);
    announcements.value = response.data.data?.announcements || [];
    pagination.value = response.data.data?.pagination || null;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Announcements] 公告列表获取成功: ${announcements.value.length} 条公告, 总条数: ${pagination.value?.totalItems || 0}`);
  } catch (error) {
    const err = error as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [Announcements] 获取公告列表失败: ${err.message}`);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [Announcements] 错误详情:`, err);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [Announcements] 响应数据:`, err?.response?.data);
    alert('获取公告数据失败');
  } finally {
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Announcements] 公告列表请求完成，loading状态设为false`);
    loading.value = false;
  }
};

/**
 * 查看公告详情
 * @param announcementId 公告ID
 */
const viewDetail = async (announcementId: number) => {
  try {
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Announcements] 开始请求查看公告详情: announcementId=${announcementId}`);
    
    const apiUrl = `${API_BASE}/api/announcements/${announcementId}`;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Announcements] 请求URL: ${apiUrl}`);
    
    const response = await axios.get(apiUrl);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Announcements] 公告详情请求成功，状态码: ${response.status}`);
    
    currentAnnouncement.value = response.data.data || null;
    showDetail.value = true;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Announcements] 公告详情获取成功，标题: ${currentAnnouncement.value?.title}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [Announcements] 公告详情数据:`, currentAnnouncement.value);
  } catch (error) {
    const err = error as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [Announcements] 获取公告详情失败: ${err.message}`);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [Announcements] 错误详情:`, err);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [Announcements] 响应数据:`, err?.response?.data);
    alert('获取公告详情失败');
  }
};

/**
 * 关闭公告详情
 */
const closeDetail = () => {
  console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Announcements] 关闭公告详情弹窗`);
  showDetail.value = false;
  currentAnnouncement.value = null;
};

/**
 * 切换页码
 * @param pageNum 目标页码
 */
const changePage = (pageNum: number) => {
  console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Announcements] 尝试切换页码: 从 ${currentPage.value} 到 ${pageNum}`);
  
  if (pageNum < 1 || (pagination.value && pageNum > pagination.value.totalPages)) {
    console.warn(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] [Announcements] 页码 ${pageNum} 超出范围，忽略请求`);
    return;
  }
  
  currentPage.value = pageNum;
  console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Announcements] 页码切换成功，新页码: ${currentPage.value}`);
  fetchAnnouncements();
};

/**
 * 生成页码范围
 */
const pageRange = computed(() => {
  if (!pagination.value) return [];
  const { currentPage, totalPages } = pagination.value;
  const range = [];
  const showPages = 5; // 显示的页码数量

  // 计算起始页码
  let startPage = Math.max(1, currentPage - Math.floor(showPages / 2));
  // 调整结束页码
  let endPage = startPage + showPages - 1;
  if (endPage > totalPages) {
    endPage = totalPages;
    startPage = Math.max(1, endPage - showPages + 1);
  }

  for (let i = startPage; i <= endPage; i++) {
    range.push(i);
  }

  return range;
});

/**
 * 格式化日期
 * @param dateStr 日期字符串
 * @returns 格式化后的日期
 */
const formatDate = (dateStr: string | null | undefined): string => {
  if (!dateStr) return '';
  return moment(dateStr).format('YYYY-MM-DD HH:mm:ss');
};

/**
 * 截断内容
 * @param content 内容
 * @param length 截断长度
 * @returns 截断后的内容
 */
const truncateContent = (content: string, length: number = 100): string => {
  // 移除HTML标签
  const plainText = content.replace(/<[^>]*>/g, '');
  if (plainText.length <= length) return plainText;
  return plainText.substring(0, length) + '...';
};

// 组件挂载时获取数据
onMounted(() => {
  console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Announcements] 组件已挂载`);
  fetchAnnouncements();
});

// 组件卸载前清理
onUnmounted(() => {
  console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [Announcements] 组件即将卸载，清理资源`);
});
</script>

<style scoped>
.announcements-container {
  max-width: 100vw;
  margin: 0 auto;
  padding: 0 2vw;
  background-color: #ffffff;
  box-sizing: border-box;
}

.content-wrapper {
  padding-top: 80px; /* 为固定导航栏预留空间 */
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #333;
}

.loading-indicator, .no-data {
  text-align: center;
  padding: 50px 0;
  color: #666;
}

.announcement-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.announcement-item {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s ease;
  cursor: pointer;
  background-color: #fff;
}

.announcement-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transform: translateY(-2px);
}

.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.announcement-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.top-tag {
  background-color: #ff4d4f;
  color: white;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

.announcement-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.announcement-content {
  font-size: 15px;
  color: #444;
  margin-bottom: 10px;
  line-height: 1.6;
}

.announcement-footer {
  font-size: 14px;
  color: #999;
  text-align: right;
}

.pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
  gap: 10px;
  flex-wrap: wrap;
}

.pagination-controls button {
  padding: 6px 12px;
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.pagination-controls button:hover:not(:disabled) {
  background-color: #f0f0f0;
}

.pagination-controls button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.pagination-controls span {
  padding: 6px 12px;
  cursor: pointer;
}

.pagination-controls span.active {
  background-color: #2563eb;
  color: white;
  border-radius: 4px;
}

.page-info {
  margin-left: 10px;
  color: #666;
  font-size: 14px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
  padding: 20px;
  position: relative;
}

.close-btn {
  position: absolute;
  top: 16px;
  right: 16px;
  font-size: 24px;
  background: none;
  border: none;
  cursor: pointer;
  color: #666;
}

.detail-title {
  font-size: 22px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #333;
}

.detail-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;
  font-size: 14px;
  color: #666;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.detail-content {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
}

.detail-content img {
  max-width: 100%;
  height: auto;
}
</style>